package com.woniuxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.dto.MenusDto;
import com.woniuxy.dto.goodsGeneralAndSmallAndBrand.*;
import com.woniuxy.entity.GoodsGeneral;
import com.woniuxy.entity.GoodsSmall;
import com.woniuxy.entity.GoodsSmaller;
import com.woniuxy.enums.CodeEnum;
import com.woniuxy.exception.GoodsSmallException;
import com.woniuxy.exception.GoodsSmallerException;
import com.woniuxy.mapper.GoodsSmallerMapper;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.AddGoodsSmallerParam;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.DeleteSmallerParam;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.ListGoodsSmallerParam;
import com.woniuxy.param.goodsGeneralAndSmallAndBrand.UpdateGoodsSmallerParam;
import com.woniuxy.service.GoodsSmallService;
import com.woniuxy.service.GoodsSmallerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.util.RedisUtil;
import com.woniuxy.util.WoniuBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 范腾龙
 * @since 2021-12-31
 * 商品三级类信息管理服务实现类
 */
@Service
public class GoodsSmallerServiceImpl extends ServiceImpl<GoodsSmallerMapper, GoodsSmaller> implements GoodsSmallerService {

    //修改做redis保存
    @Resource
    private RedisTemplate<String, List<GoodsSmallerDto>> rt;

    @Resource
    private GoodsSmallService goodsSmallService;

    /**
     * 新增三级类的信息
     *
     * @param addGoodsSmallerParam
     * @return
     */
    @ExceptionHandler(Exception.class)
    @Override
    public GoodsSmallerDto saveSmallerInfo(AddGoodsSmallerParam addGoodsSmallerParam) {

        GoodsSmaller smallerByName = getOne(new QueryWrapper<GoodsSmaller>().eq("goods_smaller_name", addGoodsSmallerParam.getGoodsSmallerName()));

//        if (null != smallerByName) throw new GoodsSmallerException("三级类信息已存在，新增失败", 1050);
        if (null != smallerByName)
            throw new GoodsSmallerException(CodeEnum.SMALLER_ADD_FAIL.getMessage(), CodeEnum.SMALLER_ADD_FAIL.getCode());

        GoodsSmall smallDB = goodsSmallService.getById(addGoodsSmallerParam.getGoodsSmallId());
        //满足新增条件 开始新增
        GoodsSmaller goodsSmaller = new GoodsSmaller();
        BeanUtils.copyProperties(addGoodsSmallerParam, goodsSmaller);
        goodsSmaller.setGoodsSmallName(smallDB.getGoodsSmallName());
        save(goodsSmaller);
        GoodsSmallerDto goodsSmallerDto = new GoodsSmallerDto();
        BeanUtils.copyProperties(goodsSmaller, goodsSmallerDto);


        List<GoodsSmallerDto> o = rt.opsForValue().get("pawn:goods:smaller:" + goodsSmaller.getGoodsSmallId());
        if (null == o || o.size() <= 0) {
        } else {
            rt.delete("pawn:goods:smaller:" + goodsSmaller.getGoodsSmallId());
        }

        return goodsSmallerDto;
    }


    /**
     * 分页+模糊查询三级类信息
     *
     * @param limitParam
     * @return
     */
    @Override
    public PageGoodsSmallerDto pageFind(ListGoodsSmallerParam limitParam) {

        QueryWrapper<GoodsSmaller> queryWrapper = new QueryWrapper<>();
        //0表示可显示，才可以查询得到
        queryWrapper.eq("goods_smaller_status", 0);
        if (null != limitParam.getKeyword()) {
            //模糊查询的条件应该是一个组合条件 即sql要加括号！
            queryWrapper.and(qw -> {
                qw.like("goods_smaller_name", limitParam.getKeyword())
                        .or()
                        .like("goods_small_name", limitParam.getKeyword());
            });
        }
        //加个按照主键降序的条件
        queryWrapper.orderByDesc("goods_smaller_id");
        IPage<GoodsSmaller> iPage = page(new Page<>(limitParam.getIndexPage(), limitParam.getPageSize()), queryWrapper);
        PageGoodsSmallerDto pageGoodsSmallerDto = new PageGoodsSmallerDto();
        //塞入当前页
        pageGoodsSmallerDto.setIndexPage(iPage.getCurrent());
        //塞入总条数
        pageGoodsSmallerDto.setTotal(iPage.getTotal());
        //塞入数据
        pageGoodsSmallerDto.setGoodsSmallerDtos(WoniuBeanUtils.copyList(iPage.getRecords(), GoodsSmallerDto.class));
        return pageGoodsSmallerDto;
    }


    /**
     * 修改三级类信息
     *
     * @param updateGoodsSmallerParam
     * @return
     */
    @Override
    public UpdateGoodsSmallerDto updateSmallerInfo(UpdateGoodsSmallerParam updateGoodsSmallerParam) {

        //先根据id查询 返回小类对象
        GoodsSmaller smallerDB = getById(updateGoodsSmallerParam.getGoodsSmallerId());
        //在判断该对象是否满足修改要求
        if (smallerDB.getGoodsSmallerStatus() == 1)
//            throw new GoodsSmallerException("该三级类信息无法修改", 1051);
            throw new GoodsSmallerException(CodeEnum.SMALLER_UPDATE_NOWAY.getMessage(), CodeEnum.SMALLER_UPDATE_NOWAY.getCode());

        BeanUtils.copyProperties(updateGoodsSmallerParam, smallerDB);
        if (updateById(smallerDB)) {
            List<GoodsSmallerDto> o = rt.opsForValue().get("pawn:goods:smaller:" + smallerDB.getGoodsSmallId());
            if (null == o || o.size() <= 0) {
            } else {
                rt.delete("pawn:goods:smaller:" + smallerDB.getGoodsSmallId());
            }
            return WoniuBeanUtils.copyObject(smallerDB, UpdateGoodsSmallerDto.class);
        }
//        throw new GoodsSmallerException("修改失败",1025);
        throw new GoodsSmallerException(CodeEnum.SMALLER_UPDATE_FAIL.getMessage(), CodeEnum.SMALLER_UPDATE_FAIL.getCode());

    }


    /**
     * 批量删除三级类信息
     *
     * @param deleteSmallerParam
     * @return
     */
    @Override
    public Boolean deleteGoodsSmaller(DeleteSmallerParam deleteSmallerParam) {

        List<GoodsSmaller> smallers = list(new QueryWrapper<GoodsSmaller>().in("goods_smaller_id", deleteSmallerParam.getGoodsSmallerIds()));
//        if (null == smallers || smallers.size() <= 0) throw new GoodsSmallerException("三级类信息不存在", 1051);
        if (null == smallers || smallers.size() <= 0)
            throw new GoodsSmallerException(CodeEnum.SMALLER_INFO_NULL.getMessage(), CodeEnum.SMALLER_INFO_NULL.getCode());

        //过滤掉不符合删除条件的数据
        List<GoodsSmaller> collect = smallers.stream().filter(smaller -> {
            Boolean flag = !(smaller.getGoodsSmallerStatus() == 1);
            //逻辑删除
            if (flag) smaller.setGoodsSmallerStatus(1);
            return flag;
        }).collect(Collectors.toList());//将符合删除条件的数据添加到新集合内
//        if (collect.size() != smallers.size()) throw new GoodsSmallerException("有三类不满足删除条件", 1011);
        if (collect.size() != smallers.size())
            throw new GoodsSmallerException(CodeEnum.SMALLER_DELETE_NOWAY.getMessage(), CodeEnum.SMALLER_DELETE_NOWAY.getCode());
        for (GoodsSmaller goodsSmaller : collect) {
            for (GoodsSmaller smaller : smallers) {
                List<GoodsSmallerDto> o = rt.opsForValue().get("pawn:goods:smaller:" + smaller.getGoodsSmallId());
                if (null == o || o.size() <= 0) {
                } else {
                    rt.delete("pawn:goods:smaller:" + smaller.getGoodsSmallId());
                }
            }

        }

        return updateBatchById(collect);
    }

    /**
     * 将三类视为父节点，将二类视为子节点，将大类视为孙子节点
     * 两个不嵌套的循环 利用map k为菜单表主键
     *
     * @return
     */
    @Override
    public List<GoodsSmallerDto> getSmallerSmallGeneral() {

//        List<GoodsSmaller> smallers = list();
//
//        List<GoodsSmallerDto> mds = WoniuBeanUtils.copyList(smallers, GoodsSmallerDto.class);
//        List<GoodsSmallerDto> resultDtos = new ArrayList<>();
//        Map<Integer, GoodsSmallerDto> map = new HashMap<>();
//
//        for (GoodsSmallerDto md : mds) {
//            if (md.getGoodsSmallId()!=null) resultDtos.add(md);
//            map.put(md.getGoodsSmallerId(), md);
//        }
//
//        for (GoodsSmallerDto md : mds) {
//            GoodsSmallerDto goodsSmaller = map.get(md.getGoodsSmallId());
//            if (goodsSmaller != null) {
//                if (goodsSmaller. == null) parent.setMenusDtoList(new ArrayList<>());
//                parent.getMenusDtoList().add(md);
//            }
//        }
        return null;
    }

    @Override
    public List<GoodsSmallerDto> listGoodsSmallerDto(Integer goodsSmallId) {
        List<GoodsSmallerDto> o = rt.opsForValue().get("pawn:goods:smaller:" + goodsSmallId);

        if (null == o || o.size() <= 0) {
            QueryWrapper<GoodsSmaller> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_smaller_status", 0).eq("goods_small_id", goodsSmallId);
            List<GoodsSmaller> list = list(queryWrapper);

            List<GoodsSmallerDto> dtos = WoniuBeanUtils.copyList(list, GoodsSmallerDto.class);
            rt.opsForValue().set("pawn:goods:smaller:" + goodsSmallId, dtos);
            rt.expire("pawn:goods:smaller:" + goodsSmallId, 30, TimeUnit.MINUTES);
            return dtos;
        } else {

            return o;
        }

    }

    @Override
    public List<GoodsSmallerDto> listGoodsSmaller() {
        QueryWrapper<GoodsSmaller> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_smaller_status", 0);
        return WoniuBeanUtils.copyList(list(queryWrapper), GoodsSmallerDto.class);
    }
}
